package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.autoconfig.template.SmsTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.dubbo.api.*;
import com.tanhua.model.domain.User;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.UserLike;
import com.tanhua.model.mongo.Visitors;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.UserVo;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.*;

@Service
public class UserService {

    @Autowired
    private SmsTemplate template;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @DubboReference
    private UserApi userApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @DubboReference
    private UserLikeApi userLikeApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private VisitorsApi visitorsApi;

    @DubboReference
    private SettingsApi settingsApi;


    /**
     * 发送短信验证码
     *
     * @param phone
     */
    public void sendMsg(String phone) {
        //1、随机生成6位数字
        //String code = RandomStringUtils.randomNumeric(6);
        String code = "123456";
        //2、调用template对象，发送手机短信
        //template.sendSms(phone,code);
        //3、将验证码存入到redis
        redisTemplate.opsForValue().set("CHECK_CODE_" + phone, code, Duration.ofMinutes(5));
    }


    /**
     * 验证登录
     *
     * @param phone
     * @param code
     */
    public Map loginVerification(String phone, String code) {
        //1、从redis中获取下发的验证码
        String redisCode = redisTemplate.opsForValue().get("CHECK_CODE_" + phone);
        //2、对验证码进行校验（验证码是否存在，是否和输入的验证码一致）
        if (StringUtils.isEmpty(redisCode) || !redisCode.equals(code)) {
            //验证码无效
            throw new RuntimeException("验证码错误");
        }
        //3、删除redis中的验证码
        redisTemplate.delete("CHECK_CODE_" + phone);
        //4、通过手机号码查询用户
        User user = userApi.findByMobile(phone);
        boolean isNew = false;
        //5、如果用户不存在，创建用户保存到数据库中
        if (user == null) {
            user = new User();
            user.setMobile(phone);
            user.setPassword(DigestUtils.md5Hex("123456"));
            Long userId = userApi.save(user);
            user.setId(userId);
            isNew = true;

            //注册环信用户
            String hxUser = "hx" + user.getId();
            Boolean create = huanXinTemplate.createUser(hxUser, Constants.INIT_PASSWORD);
            if (create) {
                user.setHxUser(hxUser);
                user.setHxPassword(Constants.INIT_PASSWORD);
                userApi.update(user);
            }
        }

        // 判断是否冻结
        String FreezingValue = redisTemplate.opsForValue().get(Constants.FreezingRange_LOGIN + user.getId());
        if (FreezingValue != null) {
            if ("never".equals(FreezingValue)) {
                throw new BusinessException(ErrorResult.FreezingLoginNeverError());
            }
            //获取当前时间毫秒值
            long NowTime = new Date().getTime();
            //获取冻结结束时间
            Long FreezingTime = Long.valueOf(FreezingValue);
            //(unFreezingHour)距离解封时间还有多少小时
            Long unFreezingHour = (FreezingTime - NowTime) / 1000 / 3600;
            throw new BusinessException(ErrorResult.FreezingLoginTimeError(unFreezingHour.toString()));
        }

        String date = new SimpleDateFormat("yyyy-MM-dd").format(new GregorianCalendar().getTime());

        String value = redisTemplate.opsForValue().get(Constants.Login_Times_Num + date);
        if (value != null) {
            Integer old = Integer.valueOf(value);
            Integer now = old + 1;
            redisTemplate.opsForValue().set(Constants.Login_Times_Num + date, Integer.toString(now), Duration.ofDays(2));
        } else {
            redisTemplate.opsForValue().set(Constants.Login_Times_Num + date, Integer.toString(1), Duration.ofDays(2));
        }


        //6、通过JWT生成token(存入id和手机号码)
        Map tokenMap = new HashMap();
        tokenMap.put("id", user.getId());
        tokenMap.put("mobile", phone);
        String token = JwtUtils.getToken(tokenMap);
        //7、构造返回值
        Map retMap = new HashMap();
        retMap.put("token", token);
        retMap.put("isNew", isNew);

        return retMap;
    }

    public Map updatePhone(String phone, String code) {
        //1、从redis中获取下发的验证码
        String redisCode = redisTemplate.opsForValue().get("CHECK_CODE_" + phone);
        //2、对验证码进行校验（验证码是否存在，是否和输入的验证码一致）
        if (StringUtils.isEmpty(redisCode) || !redisCode.equals(code)) {
            //验证码无效
            throw new RuntimeException("验证码错误");
        }
        //3、删除redis中的验证码
        redisTemplate.delete("CHECK_CODE_" + phone);

        //7、构造返回值
        Map retMap = new HashMap();
        retMap.put("verification", true);
        return retMap;
    }

    public void saveUpdatePhone(User user) {
        userApi.updatePhone(user);
    }

    public Map likeCounts() {
        //获取当前用户id
        Long userId = UserHolder.getUserId();
        //调用api获取我喜欢的
        List<UserLike> userLikes = userLikeApi.likeList(userId, true);
        //获取我喜欢的数量
        Integer loveCount = userLikes.size();
        //调用api,查询相互相互喜欢
        int eachLoveCount = 0;
        for (UserLike userLike : userLikes) {
            Long likeUserId = userLike.getLikeUserId();
            UserLike eachLike = userLikeApi.toUserLike(userId, likeUserId, true);
            if (eachLike != null) {
                eachLoveCount++;
            }
        }

        //创建返回值
        Map map = new HashMap();
        map.put("eachLoveCount", eachLoveCount);
        map.put("loveCount", loveCount);
        map.put("fanCount", 999999999);
        return map;
    }

    public PageResult friendsList(int page, int pagesize, String nickname, String type) {
        //获取当前用户Id
        Long userId = UserHolder.getUserId();
        //判断type属性
        List<Long> friendIds = new ArrayList<>();
        //封装查询条件
        UserInfo userInfo = new UserInfo();
        userInfo.setNickname(nickname);
        if ("1".equals(type)) {
            //创建一个空的UserLike集合,便于封装
            List<UserLike> userInfos = new ArrayList<>();
            //调用api取我喜欢的人
            List<UserLike> userLikes = userLikeApi.likeList(userId, true);
            //循环遍历,查找相互喜欢的人
            for (UserLike userLike : userLikes) {
                Long likeUserId = userLike.getLikeUserId();
                //调用api,查询相互喜欢
                UserLike eachLike = userLikeApi.toUserLike(userId, likeUserId, true);
                if (eachLike != null) {
                    //如果有数据,封装到新集合
                    userInfos.add(userLike);
                }
            }
            //获取新集合中所有用户id
            friendIds = CollUtil.getFieldValues(userInfos, "likeUserId", Long.class);
        } else if ("2".equals(type)) {
            //调用api取我喜欢的人
            List<UserLike> userLikes = userLikeApi.likeList(userId, true);
            friendIds = CollUtil.getFieldValues(userLikes, "likeUserId", Long.class);
        } else if ("3".equals(type)) {
            //粉丝假的
            throw new BusinessException(ErrorResult.error());
        } else {
            //创建新vos集合,便于封装
            List<UserVo> vos = new ArrayList<>();
            //调用访客api,传入当前用户id,查询访客列表
            List<Visitors> visitorsList = visitorsApi.findById(userId);
            friendIds = CollUtil.getFieldValues(visitorsList, "visitorUserId", Long.class);
            //调用userInfoApi根据ids查询所有用户信息
            if (CollUtil.isEmpty(friendIds)) {
                throw new BusinessException(ErrorResult.notError());
            }
            Map<Long, UserInfo> map = userInfoApi.findByIds(friendIds, userInfo);
            for (Visitors visitors : visitorsList) {
                UserInfo info = map.get(visitors.getVisitorUserId());
                UserVo vo = new UserVo();
                BeanUtils.copyProperties(info, vo);
                vo.setMatchRate(visitors.getScore().intValue());
                vos.add(vo);
            }
            return new PageResult(page, pagesize, 0l, vos);
        }
        //调用getUserInfos方法,获取list集合
        List<UserInfo> userInfoList = getUserInfos(friendIds, userInfo);
        //构建返回值
        PageResult pr = new PageResult(page, pagesize, 0l, userInfoList);
        return pr;
    }

    //map转化为list
    private List<UserInfo> getUserInfos(List<Long> friendIds, UserInfo userInfo) {
        //调用userInfoApi根据ids查询所有用户信息
        if (CollUtil.isEmpty(friendIds)) {
            throw new BusinessException(ErrorResult.notLikeError());
        }
        Map<Long, UserInfo> map = userInfoApi.findByIds(friendIds, userInfo);
        //创建新userInfo,封装所有用户信息
        List<UserInfo> userInfoList = new ArrayList<>();
        //遍历map,获取所有用户信息
        Set<Long> longs = map.keySet();
        for (Long key : longs) {
            //封装到userInfoList中
            userInfoList.add(map.get(key));
        }
        return userInfoList;
    }

    //取消喜欢
    public void deleteLike(Long uid) {
        //获取当前用户id
        Long userId = UserHolder.getUserId();
        //调用api,取消喜欢
        userLikeApi.deleteLike(userId, uid);
    }

    //首页喜欢
    public Boolean love(Long uid) {
        return false;
    }
}
